/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.service.datasource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import java.util.Arrays;

import static yhao.infra.service.YhaoInfraServiceProperties.DEFAULT_AUTO_TX_NAME;

/**
 * 默认自动事务配置
 *
 * @author yoara
 */
@EnableTransactionManagement
public class DefaultAutoTxConfiguration implements TransactionManagementConfigurer, ApplicationContextAware {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private ApplicationContext applicationContext;
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        String[] beans = applicationContext.getBeanNamesForType(PlatformTransactionManager.class);
        if(beans==null || beans.length==0){
            throw new IllegalStateException("自动事务配置无法找到对应的事务配置，请去除DefaultAutoTxConfiguration.class的配置");
        }
        if(beans.length>1){
            logger.warn("找到多于一个的事务配置:["+ StringUtils.join(beans,",")
                    +"],若无配置" + DEFAULT_AUTO_TX_NAME
                    +"属性，将使用第一个配置做为默认事务配置");
        }

        String defaultName = applicationContext.getBean(Environment.class).getProperty(DEFAULT_AUTO_TX_NAME);

        if(StringUtils.isNotBlank(defaultName) && Arrays.asList(beans).contains(defaultName)){
            return applicationContext.getBean(defaultName,PlatformTransactionManager.class);
        }
        return applicationContext.getBean(beans[0],PlatformTransactionManager.class);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}